require("./cart.less");
require("./../login/jquery.citys.js");

var cartItemString = require('./cartItem.string');
var shippingString = require('./shipping.string');
var cartConfirmString = require('./cart-confirm.string');
var buyNowConfirmString = require('./buy-now-confirm.string');
var _util = require("util/util.js");
var _cart = require("service/cart-service.js");
var _shipping = require("service/shipping-service.js");
var _order = require("service/order-service.js");
var _pay = require("service/pay-service.js");
var _product = require("service/product-service.js");

var page = {
  data : {
    orderNo : null
  },
  init: function () {
    this.loadCartList();
    this.loadBuyNow();
    this.bindEvent();
  },
  loadCartList: function () {
    _cart.getCartList(function (res) {
      var itemListHtml = _util.renderHtml(cartItemString, res);
      $("#cartItemsList").html(itemListHtml);
    }, function (err) {
      console.log(err);
    })
  },
  //立即购买
  loadBuyNow : function(){
    var buyNow = _util.getUrlParam("buyNow") || '';
    var productId = _util.getUrlParam("id") || '';
    var quantity = _util.getUrlParam("quantity") || '';
    if (buyNow != null && buyNow != '') {
      _shipping.list({pageSize:100},function(res){
        var shippingStringHtml = _util.renderHtml(shippingString,res);
        $(".shippingAddress").html(shippingStringHtml);
      },function(err){
        alert(err)
      })
      _product.getBookDetail({productId : productId},function(res){
        var buyNowConfirmStringHtml = _util.renderHtml(buyNowConfirmString,res);
        $(".checkedList").html(buyNowConfirmStringHtml);
        $(".quantity").append(quantity);
        var totalPrice = parseInt(res.price) * parseInt(quantity);
        var confirmPrice = "确认支付 (共计 ￥"+totalPrice+")";
        $(".payNow").html(confirmPrice);

        page.showMask();
        $('body').css('overflow-y', 'hidden')
        if ($(document).width() > 992) {
          $('#payWrap').animate({ width: 'toggle' })
        } else {
          $('#payWrap').css('top', '100%')
          $('#payWrap').show().animate({ top: '10rem' })
        }
      },function(err){
        alert(err)
      })
    }
  },
  //监听订单状态
  listenOrderStatus : function(){
    var _this = this;
    setInterval(function(){
      _order.queryOrderPayStatus({orderNo:_this.data.orderNo},function(res){
        if(res == true){
          window.location.href = "./personalCenter.html?orderNo="+_this.data.orderNo;
        }
      },function(err){
        alert(err);
      });
    } ,5e3);
  },
  orignShippingData : {},
  bindEvent: function () {
    var _this = this;
    //减少数量
    $(document).on('click', '.countControl .fa-minus', function () {
      var num = $(this).siblings('.disabled');
      if (num.html() !== '0') {
        var data = {
          productId: $(this).data("id"),
          count: parseInt(num.html()) - 1
        }
        _cart.updateCount(data, function (res) {
          var itemListHtml = _util.renderHtml(cartItemString, res);
          $("#cartItemsList").html(itemListHtml);
        }, function (err) {
          alert(err);
        })
      }

    })
    //增加数量
    $(document).on('click', '.countControl .fa-plus', function () {
      var num = $(this).siblings('.disabled');
      var stock = parseInt($(this).data("stock"));
      if (parseInt(num.html()) >= stock && !$(this).hasClass("text-dark")) {
        $(this).addClass('text-dark');
        alert("库存不足");
      } else if (parseInt(num.html()) < stock) {
        var data = {
          productId: $(this).data("id"),
          count: parseInt(num.html()) + 1
        }
        _cart.updateCount(data, function (res) {
          var itemListHtml = _util.renderHtml(cartItemString, res);
          $("#cartItemsList").html(itemListHtml);
        }, function (err) {
          alert(err);
        })
      }
    })
    //删除
    $(document).on('click', '.deleteBtn', function () {
      if (confirm("删除这个商品嘛？")) {
        var data = {
          productIds: $(this).data("id")
        }
        _cart.delete(data, function (res) {
          var itemListHtml = _util.renderHtml(cartItemString, res);
          $("#cartItemsList").html(itemListHtml);
        }, function (err) {
          alert(err);
        })
      } else {
        return false;
      }
    })
    //全选
    $(document).on("click", "#checkedAll", function () {
      _cart.selectAll(function (res) {
        var itemListHtml = _util.renderHtml(cartItemString, res);
        $("#cartItemsList").html(itemListHtml);
      }, function (err) {
        alert(err);
      })
    })
    //取消全选
    $(document).on("click", "#unCheckedAll", function () {
      _cart.unSelectAll(function (res) {
        var itemListHtml = _util.renderHtml(cartItemString, res);
        $("#cartItemsList").html(itemListHtml);
      }, function (err) {
        alert(err);
      })
    })
    //选择
    $(document).on("click", "#checked", function () {
      var data = {
        productId: $(this).data("id")
      }
      _cart.select(data, function (res) {
        var itemListHtml = _util.renderHtml(cartItemString, res);
        $("#cartItemsList").html(itemListHtml);
      }, function (err) {
        alert(err);
      })
    })
    //取消选择
    $(document).on("click", "#unChecked", function () {
      var data = {
        productId: $(this).data("id")
      }
      _cart.unSelect(data, function (res) {
        var itemListHtml = _util.renderHtml(cartItemString, res);
        $("#cartItemsList").html(itemListHtml);
      }, function (err) {
        alert(err);
      })
    })
    //提交购物车
    $(document).on('click', '#checkOutBtn', function () {
      if ($(this).data("quantity") == '0') {
        alert("购物车是空的~");
        return false;
      }
      _shipping.list({ pageSize: 100 }, function (res) {
        var shippingStringHtml = _util.renderHtml(shippingString, res);
        $(".shippingAddress").html(shippingStringHtml);
      }, function (err) {
        alert(err)
      })
      _cart.getCartList(function (res) {
        var cartConfirmHtml = _util.renderHtml(cartConfirmString, res);
        $(".checkedList").html(cartConfirmHtml);
        var confirmPrice = "确认支付 (共计 ￥" + res.cartTotalPrice + ")";
        $(".payNow").html(confirmPrice);
      }, function (err) {
        alert(err)
      })
      page.showMask();
      $('body').css('overflow-y', 'hidden')
      if ($(document).width() > 992) {
        $('#payWrap').animate({ width: 'toggle' })
      } else {
        $('#payWrap').css('top', '100%')
        $('#payWrap').show().animate({ top: '10rem' })
      }

    })
    //取消确认
    $(document).on('click', '.closeBtn', function () {
      page.hideMask();
      if ($(document).width() > 992) {
        $('#payWrap').animate({ width: 'toggle' }, function () {
          $('body').css('overflow-y', 'auto')
        })
      } else {
        $('#payWrap').animate({ top: '100%' }, function () {
          $(this).hide();
          $(this).css('top', '0')
          $('body').css('overflow-y', 'auto')
        })
      };
      page.deleteQrcode();
    })

    //选中收货地址设置为默认
    $(document).on('click', '.checkShippingCard', function () {
      var $this = $(this),
          data = {
            shippingId : $(this).parents(".shippingCard").data("shipping-id")
          }
      _shipping.setDefault(data,function(res){
        $('.checkShippingCard').parents('.shippingCard').removeClass("active");
        $($this).parents('.shippingCard').addClass("active");
      },function(err){
        alert(err);
      })
    })



    $(document).on('click', '.addCardBtn', function () {
      var cardHtml = '<div class="card border-0 shippingCard"><div class="card-header border-0 d-flex justify-content-between align-items-center"><p class="m-0">收货人：<span class="nameSaved"><input type="text" placeholder="收货人姓名" class="form-inline-control shippingName" value=""></span></p><a href="#" class="btn btn-link text-danger checkShippingCard">选择</a></div><div class="card-body"><div class="form-group "><label>收货地址</label><div class="shippingAddressWrap"><div class="citys" id="citySelecter"><div class="cityRow"><select name="province" class="province custom-select"></select><select name="city" class="city custom-select"></select></div><div class="cityRow"><select name="area" class="area custom-select"></select><select name="town" class="town custom-select"></select></div><input type="text" class="form-control addressDetail" placeholder="请输入您的详细地址" value=""></div></div></div><div class="shippingInfo d-flex justify-content-between align-items-center "><div class="form-group"><label for="shippingPhone ">手机号</label><div class="shippingPhoneWrap"><input type="text " class="form-control shippingPhone" placeholder="收货手机号" value=""></div></div><div class="form-group "><label for="shippingCode ">邮编</label><div class="shippingCodeWrap"><input type="text " placeholder="收货邮编" class="form-control shippingCode" value=""></div></div></div></div><div class="card-footer border-0 bg-white "><a href="#" class="btn text-danger addCancel"><span class="fa fa-times"> 取消</span></a><a href="#" class="btn btn-danger text-white infoSave"><span class="fa fa-save"> 保存修改</span></a></div></div>'
      $(this).before(cardHtml);
      $(this).prev().find('.shippingName').focus();
      page.city();
      $('.shippingAddress').find('.addCard').hide()
    })
    $(document).on('click', '.addCancel', function () {
      $(this).parents('.shippingCard').remove();
      $('.shippingAddress').find('.addCard').show()
    })
    $(document).on('click', '.changeInfo', function () {
      var _this = $(this);
      var card = $(this).parents('.shippingCard');
      if ($('.shippingAddress').find('.infoSave').length) {
        $('.shippingAddress').find('.infoSave').parent().before('<a class="btn disabled text-danger fa fa-times errorMessage"> 请将收货信息填写完整哦</a>')
        $('.shippingAddress').find('.infoSave').parents('.shippingCard').animate({ 'scrollTop': '0' })
        return false;
      }
      // 修改按钮样式
      $(this).parent().html('<a href="#" class="btn text-danger saveCancel"><span class="fa fa-times"> 取消</span></a><a href="#" class="btn btn-danger text-white infoSave"><span class="fa fa-save"> 保存修改</span></a>')
      $('.shippingAddress').find('.addCard').hide()
      // 修改地区input
      var provinceSaved = card.find('.provinceSaved').text();
      var citySaved = card.find('.citySaved').text();
      var areaSaved = card.find('.areaSaved').text();
      var townSaved = card.find('.townSaved').text();
      var addressDetailSaved = card.find('.addressDetailSaved').text();
      var addressWrap = card.find('.shippingAddressWrap');
      var addressHtml = '<div class="citys" id="citySelecter"><div class="cityRow"><select name="province" class="province custom-select"></select><select name="city" class="city custom-select"></select></div><div class="cityRow"><select name="area" class="area custom-select"></select><select name="town" class="town custom-select"></select></div><input type="text" class="form-control addressDetail" placeholder="请输入您的详细地址" value="' + addressDetailSaved + '"></div>'
      addressWrap.html(addressHtml);
      page.city(provinceSaved, citySaved, areaSaved);
      // 手机号
      var phoneWrap = card.find('.shippingPhoneWrap');
      var phoneSaved = phoneWrap.find('.phoneSaved').text();
      var phoneHtml = '<input type="text " class="form-control shippingPhone" placeholder="收货手机号" value="' + phoneSaved + '">';
      phoneWrap.html(phoneHtml);
      // 邮编
      var codeWrap = card.find('.shippingCodeWrap');
      var codeSaved = codeWrap.find('.codeSaved').text();
      var codeHtml = '<input type="text " placeholder="收货邮编" class="form-control shippingCode" value="' + codeSaved + '">';
      codeWrap.html(codeHtml);
      // 收货人
      var nameSaved = card.find('.nameSaved');
      var newName = nameSaved.text();
      var nameHtml = '<input type="text" placeholder="收货人姓名" class="form-inline-control shippingName" value="' + newName + '">';
      nameSaved.html(nameHtml);
      page.orignShippingData.province = provinceSaved;
      page.orignShippingData.city = citySaved;
      page.orignShippingData.area = areaSaved;
      page.orignShippingData.town = townSaved;
      page.orignShippingData.addressDetail = addressDetailSaved;
      page.orignShippingData.phone = phoneSaved;
      page.orignShippingData.code = codeSaved;
      page.orignShippingData.name = newName;
    })

    //新增收货地址
    $(document).on('click', '.infoSave', function () {
      var $this = $(this);
      var card = $(this).parents('.shippingCard');
      if (!page.checkComplete(card)) {
        if (card.find('.errorMessage').length == 0) {
          $(this).parent().before('<a class="btn disabled text-danger fa fa-times errorMessage"> 请将收货信息填写完整哦</a>')
        }
        return false;
      }
      // 修改按钮样式
      $(this).parent().html('<a href="#" class="btn text-danger changeInfo"><span class="fa fa-pencil"> 修改信息</span></a>')
      // 修改地区input
      var province = card.find('.province option:selected').html();
      var city = card.find('.city option:selected').html() ? card.find('.city option:selected').html() : '';
      var area = card.find('.area option:selected').html() ? card.find('.area option:selected').html() : '';
      var town = card.find('.town option:selected').html() ? card.find('.town option:selected').html() : '';
      var addressDetail = card.find('.addressDetail').val();
      var addressWrap = card.find('.shippingAddressWrap');
      var addressHtml = '<p><span class="provinceSaved">' + province + '</span> <span class="citySaved">' + city + '</span> <span class="areaSaved">' + area + '</span> <span class="townSaved">' + town + '</span> <span class="addressDetailSaved">' + addressDetail + '</span></p>';
      
      // 手机号
      var phoneWrap = card.find('.shippingPhoneWrap');
      var phone = phoneWrap.find('.shippingPhone').val();
      var phoneHtml = '<p class="phoneSaved">' + phone + '</p>';
      
      // 邮编
      var codeWrap = card.find('.shippingCodeWrap');
      var code = codeWrap.find('.shippingCode').val();
      var codeHtml = '<p class="codeSaved">' + code + '</p>';
      
      // 收货人
      var nameSaved = card.find('.nameSaved');
      var name = nameSaved.find('.shippingName').val();
      
      var data = {
        id : $(card).data("shipping-id"),
        receiverName : name,
        receiverPhone : phone,
        receiverProvince : province,
        receiverCity : city,
        receiverDistrict : area,
        receiverTown : town,
        receiverAddress : addressDetail,
        receiverZip : code,
      }
      _shipping.save(data,function(res){
        card.attr("data-shipping-id",res.id);
        addressWrap.html(addressHtml);
        phoneWrap.html(phoneHtml);
        codeWrap.html(codeHtml);
        nameSaved.html(name);
        card.find('.errorMessage').remove();
        $('.shippingAddress').find('.addCard').show()
      },function(err){
        console.log(err)
      });
      
    })

    $(document).on('click', '.saveCancel', function () {
      var card = $(this).parents('.shippingCard');
      var addressWrap = card.find('.shippingAddressWrap');
      var phoneWrap = card.find('.shippingPhoneWrap');
      var codeWrap = card.find('.shippingCodeWrap');
      var nameSaved = card.find('.nameSaved');
      if (!page.checkComplete(card)) {
        if (card.find('.errorMessage').length == 0) {
          $(this).parent().before('<a class="btn disabled text-danger fa fa-times errorMessage"> 请将收货信息填写完整哦</a>')
        }
        return false;
      }
      var addressHtml = '<p><span class="provinceSaved">' + page.orignShippingData.province + '</span> <span class="citySaved">' + page.orignShippingData.city + '</span> <span class="areaSaved">' + page.orignShippingData.area + '</span> <span class="townSaved">' + page.orignShippingData.town + '</span> <span class="addressDetailSaved">' + page.orignShippingData.addressDetail + '</span></p>';
      addressWrap.html(addressHtml);
      var phoneHtml = '<p class="phoneSaved">' + page.orignShippingData.phone + '</p>';
      phoneWrap.html(phoneHtml);
      var codeHtml = '<p class="codeSaved">' + page.orignShippingData.code + '</p>';
      codeWrap.html(codeHtml);
      nameSaved.html(page.orignShippingData.name);
      card.find('.errorMessage').remove();
      $('.shippingAddress').find('.addCard').show()
      $(this).parent().html('<a href="#" class="btn text-danger changeInfo"><span class="fa fa-pencil"> 修改信息</span></a>')
    })


    //提交订单
    $(document).on('click', '.payNow', function () {
      if (!$('.shippingCard').hasClass('active')) {
        alert("请选择一个收货地址！");
        return false;
      }
      
      var $this = $(this);
      //立即购买--start
      var buyNow = _util.getUrlParam("buyNow") || '';
      if (buyNow != null && buyNow != '') {
        var data = {
          addressId : $('.shippingCard.active').data("shipping-id"),
          productId :  _util.getUrlParam("id") || '',
          quantity : _util.getUrlParam("quantity") || ''
        }
        _order.createBuyNow(data,function(res){
          _pay.pay({orderNo : res.orderNo},function(res){
            console.log(res)
            _this.data.orderNo = res.orderNo;
            var qrImg = res.qrUrl;
            var qrHtml = '<div class="payQrcode card border-0"><div class="card-header btn-danger border-0 text-white d-flex justify-content-between align-items-center"><span>扫码支付</span><span class="btn text-white fa fa-times cancelPay"></span></div><div class="card-body"><img src="' + qrImg + '" width="100%" height="100%" alt=""></div></div>'
            $($this).before(qrHtml)
            $('.payQrcode').css({'opacity':'1','z-index':'9999999999'}).animate({'bottom':'3rem'});
            $($this).addClass('disabled');
            //绑定监听订单状态函数
            _this.listenOrderStatus();
          },function(err){
            alert(err)
          })
        },function(err){
          alert(err)
        })
        return false;
      }
      //立即购买--end

      var data = {
        shippingId : $('.shippingCard.active').data("shipping-id")
      }
      _order.create(data, function (res) {
        _pay.pay({ orderNo: res.orderNo }, function (res) {
          _this.data.orderNo = res.orderNo;
          var qrImg = res.qrUrl;
          var qrHtml = '<div class="payQrcode card border-0"><div class="card-header btn-danger border-0 text-white d-flex justify-content-between align-items-center"><span>扫码支付</span><span class="btn text-white fa fa-times cancelPay"></span></div><div class="card-body"><img src="' + qrImg + '" width="100%" height="100%" alt=""></div></div>'
          $($this).before(qrHtml)
          $('.payQrcode').css({ 'opacity': '1', 'z-index': '9999999999' }).animate({ 'bottom': '3rem' });
          $($this).addClass('disabled');
          //绑定监听订单状态函数
          _this.listenOrderStatus();
        }, function (err) {
          alert(err)
        })
      }, function (err) {
        alert(err)
      })
    })

    $(document).on('click', '.cancelPay', function () {
      page.deleteQrcode();
    })
  },
  deleteQrcode: function () {
    $('.payQrcode').remove();
    $('.payNow').removeClass('disabled');

    // 在这里重新渲染一遍购物车！
  },
  city: function (province, city, area, town) {
    var $town = $("#citySelecter select[name='town']");
    $town.hide().empty();
    $('#citySelecter').citys({
      province: province,
      city: city,
      area: area,
      town: town,
      onChange: function (info) {
        townFormat(info);
      }
    }, function (api) {
      var info = api.getInfo();
      townFormat(info);
    });
    var townFormat = function (info) {
      $town.hide().empty();
      if (info['code'] % 1e4 && info['code'] < 7e5) { //是否为“区”且不是港澳台地区
        $.ajax({
          url: 'http://passer-by.com/data_location/town/' + info['code'] + '.json',
          dataType: 'json',
          success: function (town) {
            $town.show();
            for (i in town) {
              $town.append('<option value="' + i + '">' + town[i] + '</option>');
            }
          }
        });
      }
    };
  },
  showMask: function () {
    $("#mask").css("height", '100%');
    $("#mask").css("width", '100%');
    $("#mask").fadeIn();
  },
  hideMask: function () {
    $("#mask").fadeOut();
  },
  checkComplete: function (ele) {
    var result = true;
    ele.find('input').each(function () {
      if (!$(this).val()) {
        result = false;
        return false;
      }
    })
    ele.find('select').each(function () {
      if (!$(this).val() == undefined) {
        result = false;
        return false;
      }
    })
    return result;
  }
}

$(function () {
  page.init();
})